//
//  MainViewController.m
//  Peso Guide
//
//  Created by macbook on 2025/6/5.
//

#import "MainViewController.h"
#import "BaseTableView.h"
#import "MainHeaderView.h"
#import "MainProcessCell.h"
#import "MainBannerCell.h"
#import "MainProductCell.h"
#import "MJRefresh/MJRefresh.h"
#import <CoreLocation/CoreLocation.h>
#import <UserNotifications/UserNotifications.h>
#import "DeviceInfoCollector.h"
#import "CustomWebViewController.h"
#import "MineSettingViewController.h"
#import "ProductDetailViewController.h"

@interface MainViewController ()<UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate>

@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong) NSMutableArray *bannerArray;
@property (nonatomic, strong) NSMutableArray *mainTopArray;
@property (nonatomic, strong) NSMutableArray *productArray;

@property (strong, nonatomic) CLLocationManager *locationManager;
@property (nonatomic, assign) BOOL isFirstLaunch; // 是否首次启动

@end

@implementation MainViewController

// 存储弹窗日期的Key
static NSString *const kLastAlertDateKey = @"LastLocationAlertDate";

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self loadMain];
    [self checkLocationAuthorization];
    [self upIDFAIDFV];
    [self upLoadDeviceInfo];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.backColor = ColorHex(@"#1A7A35");
    UIImageView *backImgView = [PesoKit createImageViewWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) imageNamed:@"bg_main_back_img"];
    [self.view addSubview:backImgView];
    
    self.navView.hidden = YES;
    self.titleLabel.hidden = YES;
    self.backButton.hidden = YES;
    
    [self.view addSubview:self.tableView];
    WeakSelf;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadMain];
        [weakSelf checkLocationAuthorization];
        [weakSelf upIDFAIDFV];
        [weakSelf upLoadDeviceInfo];
    }];
    
    UIImageView *topImg = [PesoKit createImageViewWithFrame:CGRectMake((KScreenWidth-134.19)/2.0, KStatusBarHeight+20, 134.19, 32.12) imageNamed:@"ic_main_top_img"];
    [self.view addSubview:topImg];
    
    _bannerArray = [NSMutableArray arrayWithCapacity:0];
    _mainTopArray = [NSMutableArray arrayWithCapacity:0];
    _productArray = [NSMutableArray arrayWithCapacity:0];
    
    [self setupLocationManager];
}

- (void)loadMain {
    [[AWHttpService service] getWithUrl:@"/trains/narrowly" params:@{} succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
    
//    NSDictionary *responseObject = [AppTools dictionaryWithJsonString:@"{\"interchangeably\":\"0\",\"order\":\"success\",\"associating\":{\"desire\":{\"experience\":\"https://dphone.png\",\"simulate\":\"http://aboutus\",\"parent\":\"http://customerService\",\"variety\":\"http://47.103.73.105:8998/#/customerService\"},\"unnested\":\"http://aliyun.com\",\"assigns\":[\"Register today and get a good gift of 2000\",\"Register today and get a good gift of 5030\"],\"below\":[{\"unboundlocalerror\":\"declareda\",\"stdin\":[{\"recent\":\"\",\"traceback\":\"https://yinni-files-dev.oss-cn-shanghai.aliyuncs.com/commonpic/kilatbanner.png\"}]},{\"unboundlocalerror\":\"declaredb\",\"stdin\":[{\"causes\":1,\"allowed\":\"Leaf Cash\",\"raised\":\"http://incashtvylw8wkt.png\",\"assigning\":\"APPLY\",\"follows\":\"₹ 2000\",\"exception\":\"Maxium Loan Amount Upto\",\"raises\":\"91 days\",\"basis\":\"Loan Term\",\"buffer\":\"0.05% day\",\"per\":\"Interest Rate\",\"now\":\"https://daninjam.png\",\"defdynamic\":\"https://danbunga.png\"}]},{\"unboundlocalerror\":\"declaredd\",\"stdin\":[{\"causes\":1000459,\"allowed\":\"矩阵测试\",\"follows\":\"Rp 1.000.000\",\"marked\":[\"Suku bunga rendah\",\"Umur 17 tahun keatas boleh pinjam\"],\"ordinary\":\"Umur 17 tahun keatas boleh pinjam\",\"raised\":\"http://danak.png\",\"assigning\":\"Segera ambil\",\"islisp\":\"yellow\",\"exception\":\"Jumlah maksimum\",\"per\":\"Bunga ≥ 0.05%/hari\",\"clojure\":1,\"adopted\":\"\",\"clumsily\":\"2\",\"operation\":1,\"expect\":\"0\",\"optimization\":\"Bunga ≥ 0.05%/hari\",\"recent\":\"\",\"raises\":\"91Hari\",\"basis\":\"Loan Term\",\"treated\":[],\"special\":\"\",\"inspired\":[],\"root\":100,\"path\":\"1000000\",\"buffer\":\"\"}]}]}}"];
    
            NSDictionary *associating = [responseObject safeObjectForKey:@"associating"];
            NSMutableArray *unboundlocalerrors = [NSMutableArray safeArrayWithArray:[associating safeObjectForKey:@"below"]];
            [self.bannerArray removeAllObjects];
            [self.mainTopArray removeAllObjects];
            [self.productArray removeAllObjects];
            
            for (int i = 0; i < unboundlocalerrors.count; i++) {
                NSDictionary *unboundlocalerrorsDic = [NSDictionary safeDictionaryWithDictionary:[unboundlocalerrors safeObjectAtIndex:i]];
                NSString *unboundlocalerror = [NSString stringWithFormat:@"%@",[unboundlocalerrorsDic safeObjectForKey:@"unboundlocalerror"]];
                if ([unboundlocalerror isEqualToString:@"declareda"]) {
                    //banner
                    NSArray *stdin = [NSArray safeArrayWithArray:[unboundlocalerrorsDic safeObjectForKey:@"stdin"]];
                    [self.bannerArray addObjectsFromArray:stdin];
                }
                if ([unboundlocalerror isEqualToString:@"declaredb"] || [unboundlocalerror isEqualToString:@"declaredc"]) {
                    //首页Top
                    NSDictionary *stdin = [unboundlocalerrorsDic safeObjectForKey:@"stdin"];
                    [self.mainTopArray addObject:stdin];
                }
//                if ([unboundlocalerror isEqualToString:@"declaredc"]) {
//                    //产品列表
//                    [self.productArray addObjectsFromArray:[unboundlocalerrorsDic safeObjectForKey:@"stdin"]];
//                }
                if ([unboundlocalerror isEqualToString:@"declaredd"]) {
                    //产品列表
                    [self.productArray addObjectsFromArray:[unboundlocalerrorsDic safeObjectForKey:@"stdin"]];
                }
                [self.tableView reloadData];
            }
        }else {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]]];
            [SVProgressHUD dismissWithDelay:3.0f];

        }
        [self.tableView.mj_header endRefreshing];
        
    } fail:^(NSInteger errorType, id  _Nonnull error) {}];
    
    [self.tableView.mj_header endRefreshing];

    [[AWHttpService service] getWithUrl:@"/trains/experience" params:@{} succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            NSDictionary *associating = [NSDictionary safeDictionaryWithDictionary:[responseObject safeObjectForKey:@"associating"]];
            NSArray *addressArray = [NSArray safeArrayWithArray:[associating safeObjectForKey:@"below"]];
            
            NSString *json = [AppTools jsonStringWithNSArray:addressArray];
            
            [[NSUserDefaults standardUserDefaults] setObject:json forKey:@"app_city_json"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {
    }];
}

- (void)upIDFAIDFV {
    [[AWHttpService service] postWithUrl:@"/trains/variety" params:@{@"associates":[AppTools getOrCreatePseudoIDFV],@"table":[AppTools getIDFA]} succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            DLog(@"Reported successfully");
        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {
        
    }];
}

- (void)upLoadDeviceInfo {
    NSDictionary *deviceInfo = [DeviceInfoCollector collectDeviceInfo];
    [[AWHttpService service] postWithUrl:@"/trains/parent" params:@{@"associating":[AppTools jsonStringWithDictionary:deviceInfo]} succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            DLog(@"Reported successfully");
        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {
        
    }];
}

#pragma mark - UITableViewDelegate&UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2+_productArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        NSString *MainBannerCellIdentifier = [NSString stringWithFormat:@"MainBannerCellIdentifier%ld",(long)indexPath.row];
        MainBannerCell *cell = [tableView dequeueReusableCellWithIdentifier:MainBannerCellIdentifier];
        if (!cell) {
            cell = [[MainBannerCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainBannerCellIdentifier];
            cell.clipsToBounds = YES;
        }
        if (self.bannerArray.count > 0) {
            cell.bannerList = self.bannerArray;
        }
        return cell;
    }else if (indexPath.row == 1) {
        NSString *MainProcessCellIdentifier = [NSString stringWithFormat:@"MainProcessCellIdentifier%ld",(long)indexPath.row];
        MainProcessCell *cell = [tableView dequeueReusableCellWithIdentifier:MainProcessCellIdentifier];
        if (!cell) {
            cell = [[MainProcessCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainProcessCellIdentifier];
            cell.clipsToBounds = YES;
        }
        return cell;
    }else {
        NSString *MainProductCellIdentifier = [NSString stringWithFormat:@"MainProductCellIdentifier%ld",(long)indexPath.row];
        MainProductCell *cell = [tableView dequeueReusableCellWithIdentifier:MainProductCellIdentifier];
        if (!cell) {
            cell = [[MainProductCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainProductCellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (self.productArray.count > 0) {
            cell.dataDic = [self.productArray safeObjectAtIndex:indexPath.row-2];
        }
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        if (self.bannerArray.count == 0) {
            return 0.01f;
        }
        if (self.productArray.count > 0) {
            return 0.01f;
        }
        return ceil((KScreenWidth-40)*0.29253)+20;
    }else if (indexPath.row == 1) {
        if (self.productArray.count > 0) {
            return 0.01f;
        }
        return ceil((KScreenWidth-40)*0.65373)+10;
    }else {
        return 95+16;
    }
    return 0.01f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    MainHeaderView *headerView = [[MainHeaderView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, ceil((KScreenWidth-24)*0.96+10))];
    headerView.clipsToBounds = YES;
    if (self.mainTopArray.count > 0) {
        headerView.topList = self.mainTopArray;
    }
    if (self.mainTopArray.count == 0 || self.mainTopArray == nil) {
        headerView.height = 0.01f;
    }
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.mainTopArray.count == 0 || self.mainTopArray == nil) {
        return 0.01f;
    }
    return ceil((KScreenWidth-24)*0.96)+20;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    kPreventRepeatClickTime(1.5);
    if (indexPath.row == 0 || indexPath.row == 1) {
        return;
    }else {
        NSDictionary *dataDic = [NSDictionary safeDictionaryWithDictionary:[self.productArray safeObjectAtIndex:indexPath.row-2]];
        NSString *causes = [NSString stringWithFormat:@"%@",[dataDic safeObjectForKey:@"causes"]];
        
        [[AWHttpService service] postWithUrl:@"/trains/synonymous" params:@{@"across":causes} succ:^(id  _Nonnull responseObject) {
            if (SUCCESS) {
                NSDictionary *associating = [NSDictionary safeDictionaryWithDictionary:[responseObject safeObjectForKey:@"associating"]];
                NSString *recent = [NSString stringWithFormat:@"%@",[associating safeObjectForKey:@"recent"]];
                
                if ([recent rangeOfString:@"http://"].location != NSNotFound ||
                    [recent rangeOfString:@"https://"].location != NSNotFound) {
                    //webView
                    CustomWebViewController *webVC = [[CustomWebViewController alloc] init];
                    webVC.linkUrl = recent;
                    [[AppTools getCurrentVC].navigationController pushViewController:webVC animated:YES];
                    return;
                }
                if ([recent rangeOfString:@"pe://so.gui.de/thelike"].location != NSNotFound) {
                    //设置
                    MineSettingViewController *settingVC = [[MineSettingViewController alloc] init];
                    settingVC.hidesBottomBarWhenPushed = YES;
                    [[AppTools getCurrentVC].navigationController pushViewController:settingVC animated:YES];
                    return;
                    return;
                }
                if ([recent rangeOfString:@"pe://so.gui.de/andlove"].location != NSNotFound) {
                    //首页
                    [AppTools getCurrentVC].tabBarController.selectedIndex = 0;
                    return;
                }
                if ([recent rangeOfString:@"pe://so.gui.de/standard"].location != NSNotFound) {
                    //登录
                    [AppTools toLogin];
                    return;
                }
                if ([recent rangeOfString:@"pe://so.gui.de/classes"].location != NSNotFound) {
                    //订单
                    [AppTools getCurrentVC].tabBarController.selectedIndex = 1;
                    return;
                }
                if ([recent rangeOfString:@"pe://so.gui.de/islove"].location != NSNotFound) {
                    //产品详情
                    NSArray *array = [recent componentsSeparatedByString:@"="];
                    NSString *theId = @"";
                    if (array.count == 2) {
                        theId = [NSString stringWithFormat:@"%@",[array safeObjectAtIndex:1]];
                    }else {
                        theId = causes;
                    }
                    ProductDetailViewController *vc = [[ProductDetailViewController alloc] init];
                    vc.productId = theId;
                    vc.hidesBottomBarWhenPushed = YES;
                    [[AppTools getCurrentVC].navigationController pushViewController:vc animated:YES];
                    return;
                }
            }else {
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[responseObject safeObjectForKey:@"order"]]];
                [SVProgressHUD dismissWithDelay:3.0f];

            }
        } fail:^(NSInteger errorType, id  _Nonnull error) {}];
    }
}

// 初始化定位管理器
- (void)setupLocationManager {
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
}

// 检查定位权限
- (void)checkLocationAuthorization {
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
    // 首次启动且未请求过权限
    if (status == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    // 用户已拒绝权限
    else if (status == kCLAuthorizationStatusDenied) {
        NSString *location = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_show_location"];
        if ([location isEqualToString:@"1"]) {
            //1 弹 2 不弹
            [self showLocationAlertIfNeeded];
        }
    }
    // 已授权则开始定位
    else if (status == kCLAuthorizationStatusAuthorizedWhenInUse ||
             status == kCLAuthorizationStatusAuthorizedAlways) {
        [self startUpdatingLocation];
    }
}

// 显示定位提醒弹窗（每天只提示一次）
- (void)showLocationAlertIfNeeded {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDate *lastAlertDate = [defaults objectForKey:kLastAlertDateKey];
    NSDate *today = [NSDate date];
    
    // 检查今天是否已经弹过窗
    if (lastAlertDate && [self isSameDay:lastAlertDate date2:today]) {
        return;
    }
    
    // 记录本次弹窗日期
    [defaults setObject:today forKey:kLastAlertDateKey];
    [defaults synchronize];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:[Lang set:@"The location permission has been disabled"]
                                                                   message:[Lang set:@"You have denied the location permission, which will affect the use of some functions. Do you want to go to Settings to enable it?"]
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    // 前往设置按钮
    UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:[Lang set:@"Set it up"]
                                                             style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * _Nonnull action) {
        [self openAppSettings];
    }];
    
    // 取消按钮（不阻塞流程）
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:[Lang set:@"Cancel"]
                                                           style:UIAlertActionStyleCancel
                                                         handler:nil];
    
    [alert addAction:settingsAction];
    [alert addAction:cancelAction];
    
    [self presentViewController:alert animated:YES completion:nil];
}

// 跳转到应用设置
- (void)openAppSettings {
    NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
        [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
    }
}

// 开始定位
- (void)startUpdatingLocation {
    [self.locationManager startUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    [self checkLocationAuthorization];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *currentLocation = [locations lastObject];
    
    // 停止定位以节省电量
    [manager stopUpdatingLocation];
    
    // 反向地理编码获取地址信息
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error || placemarks.count == 0) {
            DLog(@"location error: %@", error.localizedDescription);
            return;
        }
        
        CLPlacemark *placemark = [placemarks firstObject];
        [self handleLocationInfo:placemark location:currentLocation];
    }];
}

// 处理定位信息
- (void)handleLocationInfo:(CLPlacemark *)placemark location:(CLLocation *)location {
    // 提取所需信息
    NSString *province = placemark.administrativeArea;      // 省
    NSString *countryCode = placemark.ISOcountryCode;       // 国家代码
    NSString *country = placemark.country;                  // 国家
    NSString *street = [NSString stringWithFormat:@"%@%@",
                        placemark.thoroughfare ?: @"",
                        placemark.subThoroughfare ?: @""];   // 街道
    CLLocationDegrees latitude = location.coordinate.latitude;   // 纬度
    CLLocationDegrees longitude = location.coordinate.longitude; // 经度
    NSString *city = placemark.locality;                    // 市
    NSString *district = placemark.subLocality;             // 区
    
    // 在此处使用获取到的定位信息（示例打印）
    DLog(@"location: guojia=%@, daima=%@, sheng=%@, shi=%@, qu=%@, jiedao=%@, weidu=%f, jingdu=%f",
          country, countryCode, province, city, district, street, latitude, longitude);
    
    NSDictionary *params = @{@"lifo":[AppTools isEmpty:province]?@"":province,
                             @"last":[AppTools isEmpty:countryCode]?@"":countryCode,
                             @"strategies":[AppTools isEmpty:country]?@"":country,
                             @"taken":[AppTools isEmpty:street]?@"":street,
                             @"care":[NSString stringWithFormat:@"%f",latitude],
                             @"search":[NSString stringWithFormat:@"%f",longitude],
                             @"linear":[AppTools isEmpty:city]?@"":city,
                             @"meanings":[AppTools isEmpty:district]?@"":district};
    [[AWHttpService service] postWithUrl:@"/trains/simulate" params:params succ:^(id  _Nonnull responseObject) {
        if (SUCCESS) {
            DLog(@"Reported successfully");
        }
    } fail:^(NSInteger errorType, id  _Nonnull error) {}];
}

// 工具方法：判断两个日期是否同一天
- (BOOL)isSameDay:(NSDate *)date1 date2:(NSDate *)date2 {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents *comp2 = [calendar components:unitFlags fromDate:date2];
    
    return [comp1 day] == [comp2 day] &&
           [comp1 month] == [comp2 month] &&
           [comp1 year] == [comp2 year];
}

#pragma mark - lazy load
- (BaseTableView *)tableView {
    if (!_tableView) {
        _tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, KStatusBarHeight+20+15+32.12, KScreenWidth, KScreenHeight-(KStatusBarHeight+20+15+32.12)-kStatusBarHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
